<?php

namespace App\Http\Controllers\Admin;

use App\Models\Animation;
use App\Models\AnimationCategory;
use Illuminate\Http\Request;
use App\Org\Developer\Helper;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class AnimationController extends Controller
{
  /**
     * 动画列表首页
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        return view('admin.animation.index');
    }

    /**
     * 异步获取列表数据
     *
     * @param Request $request
     *
     * @return array
     */
    public function lists(Request $request)
    {
        if ($request->ajax()) {            
            $offset = intval($request->get('start'));
            $paginate = Animation::select(['animations.id', 'animations.name', 'animations.category_id', 'animation_categories.name AS category_name', 'animations.created_at'])
                ->join('animation_categories', function ($join) {
                    $join->on('animation_categories.id', '=', 'animations.category_id');
                })
                ->orderBy('animations.id', 'desc')
                ->paginate(self::PAGE_SIZE, ['*'], 'page', intval($offset / self::PAGE_SIZE) + 1);

            $data = [];
            foreach ($paginate as $item) {
                $data[] = [
                    $item->id,
                    $item->name,
                    $item->category_name,
                    $item->created_at->toDateTimeString(),
                    // '<a type="button" class="btn btn-primary btn-xs">查看</a>',
                    '<a href="'. url('admin/animation/' . $item->id) .'/edit" type="button" class="btn btn-primary btn-xs"><i class="fa fa-pencil"></i> 修改</a> <a type="button" class="btn btn-danger btn-xs btn-remove" data-id="'. $item->id .'"><i class="fa fa-remove"></i> 删除</a>',
                ];
            }

            $records = [
                'data' => $data,
                'draw' => intval($request->get('draw')),
                'recordsTotal' => $paginate->total(),
                'recordsFiltered' => $paginate->total(),
            ];

            return response()->json($records);
        } else {
            return redirect()->guest('admin/login');
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $categoryModels = AnimationCategory::select(['id', 'name'])->get();
        return view('admin.animation.create')->with(['categoryModels' => $categoryModels]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            $this->validate($request, [
                'name' => 'required|min:2',
                'classname' => 'required',
                'category_id' => 'required',
                'content' => 'required'
            ], [
                'required' => ':attribute 必须.',
                'min' => ':attribute 不能少于 2 位.'
            ]);

            $postData = [
                'name' => $request->input('name'),
                'classname' => $request->input('classname'),
                'category_id' => $request->input('category_id'),
                'content' => $request->input('content')
            ];
            $createModel = Animation::create($postData);
            if (isset($createModel) && $createModel->id) {
                return redirect('admin/animation');
            }
            return back()->with('status', '动画添加失败.');
        } catch (\Exception $e) {
            return back()->with('status', '动画添加失败.'. $e->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return back()->with('status', '动画 id 不合法.');
        }
        try {
            $categoryModels = AnimationCategory::select(['id', 'name'])->get();

            $updateModel = Animation::select(['id', 'name', 'classname', 'content', 'category_id'])->find($id);
            if (!(isset($updateModel) && $updateModel->name)) {
                return redirect('admin/animation')->with('status', '要修改的动画不存在.');
            }
            return view('admin.animation.update')->with(['model' => $updateModel, 'categoryModels' => $categoryModels]);
        } catch (\Exception $e) {
            return back()->with('status', '动画修改失败.'. $e->getMessage());
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return back()->with('status', '动画 id 不合法.');
        }

        try {
            // 检查动画是否存在
            $updateModel = Animation::select(['id', 'name'])->find($id);
            if (!(isset($updateModel) && $updateModel->name)) {
                return redirect('admin/animation')->with('status', '要修改的动画不存在.');
            }

            $this->validate($request, [
                'name' => 'required|min:2',
                'classname' => 'required',
                'category_id' => 'required',
                'content' => 'required'
            ], [
                'required' => ':attribute 必须.',
                'min' => ':attribute 不能少于 2 位.'
            ]);

            $updateModel->name = $request->input('name');
            $updateModel->classname = $request->input('classname');
            $updateModel->category_id = $request->input('category_id');
            $updateModel->content = $request->input('content');

            $result = $updateModel->save();
            if ($result) {
                return redirect('admin/animation');
            }
            return back()->with('status', '动画修改失败.');
        } catch (\Exception $e) {
            echo "<pre>";
            print_r($e->getMessage());exit;
            return back()->with('status', '动画修改失败.'. $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        // 检查 id 是否合法
        if (Helper::idInvalid($id)) {
            return response()->json(['code' => 4000]);
        }

        try {
            // 检查该动画是否存在
            $updateModel = Animation::select(['id', 'name'])->find($id);
            if (!(isset($updateModel) && $updateModel->name)) {
                return response()->json(['code' => 4001]);
            }

            $result = $updateModel->delete();
            if ($result) {
                return response()->json(['code' => 200]);
            }
            return response()->json(['code' => 4002]);
        } catch (\Exception $e) {
            return response()->json(['code' => 5555]);
        }
    }
}